<script setup>
// import SltFromTable from '@/components/SltFromTable/SltFromTable.vue'
// import WuziXs from '@/views/WuziManage/WuziXs/WuziXs.vue'
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import api from '@/api/index.js'
// import SltFromApi from '@/components/SltFromApi/SltFromApi.vue'
import { getOptions, getConsants } from '@/utils/index.js'
import { Modal } from 'ant-design-vue'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  },
})
const testList = ref()
const options = ref()
const testOptions = async (para) => {
  const {
    data: { records }
  } = await api.getKcList(para)
  testList.value = records.map((item) => ({ label: item.productName, value: item.id }))
  // options.value = records.map((item) => ({ label: item.productName, value: item.id }))
  options.value = records
}
testOptions({ size: 9999 })
// 弹窗标题
const title = computed(() => (props.curRow.id ? '编辑数据' : '新增数据'))
// 表单数据
const formData = ref({
  type: 2,
  productType: '',
  productName: '',
  specs: '',
  quantity: '',
  unit: '',
  notes: '',
  supplier: '',
  accepterId: '',
  accepterName: '',
  storageId: '',
  storageName: '',
  accepterDeptName: ''
})
// 是否显示弹窗
const show = ref(false)
// 同步表格数据到表单数据内
watch(
  () => props.curRow,
  async (val) => {
    let resObj = {}
    if (props.curRow.id && show.value) {
      // const { resultObject } = await api.getCrkInfo({ id: props.curRow.id })
      // resObj = {resultObject}
      formData.value = { ...formData.value, ...val, ...resObj }
    } else {
      formData.value = {
        type: 2,
        productType: '',
        productName: '',
        specs: '',
        quantity: '',
        unit: '',
        // price: '',
        notes: '',
        supplier: '',
        accepterId: '',
        accepterName: '',
        storageId: '',
        storageName: '',
        accepterDeptName: ''
      }
    }
  },
  { deep: true, immediate: true }
)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {
      type: 2,
      productType: '',
      productName: '',
      specs: '',
      quantity: '',
      unit: '',
      notes: '',
      supplier: '',
      accepterId: '',
      accepterName: '',
      storageId: '',
      storageName: '',
      accepterDeptName: ''
    }
    emits('close')
  }
}
const faMenuSltOpt = ref({})
//获取部门数据
const getList = async () => {
  const data = {
    current: 1,
    size: 100,
    total: 0
  }
  const { resultObject } = await api.getDepList(data)
  faMenuSltOpt.value = resultObject
}
getList()
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      outBigTypeName: getConsants('inventory_big_type', info.outBigTypeId),
      productName: getConsants('inventory_small_type', info.outSmallTypeId),
      outTypeName: getConsants('inventory_type', info.outTypeId)
    }
    await api.editCrk(params)
    message.success('编辑成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('reload')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}

let getCk = {}
//获取表格数据规格
// const getRows = (row, id) => {
//   if (id) {
//     getCk = row.filter((item) => item.id === id)[0]
//     formData.value.specs = getCk.specs
//     formData.value.unit = getCk.unit
//     // console.log(getCk)
//   }
// }
const changeOptions = (id) => {
  getCk = options.value.filter((item) => item.id === id)[0]
  formData.value.specs = getCk.specs
  formData.value.unit = getCk.unit
}
// 新增数据
const addItem = async (info) => {
  try {
    let list = ''
    if (formData.value?.accepterDeptName) {
      formData.value?.accepterDeptName.forEach((item) => {
        list = list + '/' + item
      })
      formData.value.accepterDeptName = list
    }
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info
    }
    params.productName = getCk.productName
    await api.addCrk(params)
    message.success('新增成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('init')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 表单提交，验证通过了
const onFinish = (values) => {
  Modal.warning({
    title: '提示',
    content: '请确认信息无误后提交，提交后信息将无法修改！',
    okText: '确认提交',
    okCancel: true,
    cancelText: '检查一下',
    onOk: async () => {
      if (formData.value.id) {
        emitItem(values)
      } else {
        addItem(values)
      }
      return Promise.resolve()
    },
    onCancel: () => {
      message.success('取消提交')
      return Promise.resolve()
    }
  })
}
// 验证失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
// 打开弹窗
const open = () => {
  show.value = true
}
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value.validateFields().then(onFinish).catch(onFinishFailed)
}
defineExpose({ open })
</script>

<template>
  <a-drawer :maskClosable="false" :closable="false" destroyOnClose v-model:open="show" class="custom-class"
    root-class-name="root-class-name" :title="title" placement="right" @after-open-change="afterOpenChange">
    <a-form ref="formRef" :model="formData" layout="vertical" autocomplete="off" @finish="onFinish"
      @finishFailed="onFinishFailed">
      <a-form-item label="物资名称" name="productName" :rules="[{ required: true, message: '请输入' }]">
        <a-select v-model:value="formData.productName" allowClear :options="testList"
          :fieldNames="{ label: 'label', value: 'value' }" @change="changeOptions" />
        <!-- <SltFromApi v-model="formData.productName" :getRows="getRows" /> -->
      </a-form-item>
      <a-form-item label="数量" name="quantity" :rules="[{ required: true, message: '请输入' }]">
        <a-input-number  :min="0" v-model:value="formData.quantity" allowClear />
      </a-form-item>
      <a-form-item label="单位" name="unit" :rules="[{ required: true, message: '请选择' }]">
        <a-select v-model:value="formData.unit" allowClear :options="getOptions('unit')"
          :fieldNames="{ label: 'constLabel', value: 'constLabel' }" disabled />
      </a-form-item>
      <a-form-item label="规格" name="specs" :rules="[{ required: true, message: '请选择' }]">
        <!-- <a-input v-model:value="formData.specs" allowClear /> -->
        <a-select v-model:value="formData.specs" allowClear disabled />
      </a-form-item>
      <a-form-item label="领用人员" name="accepterName">
        <a-input v-model:value="formData.accepterName" allowClear />
      </a-form-item>
      <a-form-item label="出库人员" name="storageName">
        <a-input v-model:value="formData.storageName" allowClear />
      </a-form-item>
      <a-form-item label="领用部门/子公司" name="storageName">
        <!-- <a-input v-model:value="formData.accepterDeptName" allowClear /> -->
        <a-cascader v-model:value="formData.accepterDeptName" :options="faMenuSltOpt" allowClear expand-trigger="hover"
          :fieldNames="{ children: 'children', label: 'name', value: 'name' }" :showSearch="true" change-on-select />
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading">提交</a-button>
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>